package com.collect.senegal;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.multidex.MultiDex;

import com.alibaba.android.arouter.launcher.ARouter;
import com.collect.senegal.zhiDi.zhiComponent.ApplicationComponent;
import com.collect.senegal.zhiDi.zhiComponent.DaggerApplicationComponent;
import com.collect.senegal.zhiDi.zhiModule.ApplicationModule;
import com.collect.senegal.zhiGlobal.zhiAppSettings.ZHIProjectConfigs;
import com.collect.senegal.zhiGlobal.zhiHandler.ZHICrashHelper;
import com.collect.senegal.zhiHelper.ZHIAdvertIDHelper;
import com.collect.senegal.zhiHelper.ZHICallLogHelper;
import com.collect.senegal.zhiUtils.MyLogger;
import com.collect.senegal.zhiUtils.ToastUtil;
import com.collect.senegal.zhiUtils.zhiKeyboardUtil.KeyboardVisibilityObserver;
import com.zhi.inisyccalllog.ASCallLogBuilder;
import com.zhi.inisyccalllog.ASCallLogManager;
import com.zhi.inisyccalllog.ASCallLogReportPolicy;
import com.zhi.inisyccalllog.ASFetchQueue;
import com.zhi.syc.data_applist.ASBuilder;
import com.zhi.syc.data_applist.ASGpsManager;
import com.zhi.syc.data_applist.ASSycManager;

public class MyApplication extends Application {
    static final String PROCESS = "com.collect.senegal";
    private static boolean mIsAppInBackgroundLast;
    static MyApplication myApplication;
    private ApplicationComponent mApplicationComponent;

    public MyApplication getApplication() {
        return myApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        myApplication = this;
        //适配android p
        initPieWebView();

        ZHIAdvertIDHelper.getInstance().init();
        ToastUtil.init(this);

        ZHICrashHelper zhiCrashHelper = ZHICrashHelper.getInstance();
        zhiCrashHelper.init(this);

        initApplicationComponent();
        intARouter();

        KeyboardVisibilityObserver.getInstance().init(this);

        //日志初始化
        MyLogger.init(BuildConfig.DEBUG, ZHIProjectConfigs.PACKAGE_NAME);
        MultiDex.install(this);

        //ini call log sdk
        initIniCallLogSdk();
        initIniSycDataSDK();

        registerActivityLifecycleCallbacks(new MyApplicationLifecycleCallbacks());
    }

    private void intARouter() {
        if (BuildConfig.DEBUG) {
            ARouter.openLog();
            ARouter.openDebug();
        }
        ARouter.init(this);
    }

    public Context getContext() {
        return this;
    }

    public ApplicationComponent getApplicationComponent() {
        return mApplicationComponent;
    }

    /**
     * 初始化ApplicationComponent
     */
    private void initApplicationComponent() {
        mApplicationComponent = DaggerApplicationComponent.builder()
                .applicationModule(new ApplicationModule(this))
                .build();
    }

    public static Context getAppContext() {
        return myApplication.getApplicationContext();
    }

    public static MyApplication getApp() {
        return myApplication;
    }

    //适配android 9网络进程
    private void initPieWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            String processName = getProcessName(this);
            if (!PROCESS.equals(processName)) {
                WebView.setDataDirectorySuffix(processName);
            }
        }
    }

    public String getProcessName(Context context) {
        if (context == null) return null;
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            if (processInfo.pid == android.os.Process.myPid()) {
                return processInfo.processName;
            }
        }
        return "COLLECTIONTOOL";
    }

    @SuppressLint("ObsoleteSdkInt")
    private void initIniCallLogSdk() {
        //初始化
        ASCallLogBuilder.setMock(false);
        ASCallLogBuilder.setLog(false);
        ASCallLogBuilder.setReportPolicy(ASCallLogReportPolicy.POLICY_REPORT_EVERY_60_MINUTE);
        ASCallLogBuilder.setServerHost(ZHIProjectConfigs.DEFAULT_URL);

        ASCallLogManager.clean();
        ASCallLogManager.testClean();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ASFetchQueue.getInstance().init(this);
        }
    }

    private void initIniSycDataSDK() {
        try {
            ASBuilder.setMock(false);
            ASBuilder.setLog(false);
            ASBuilder.setServerHost(ZHIProjectConfigs.DEFAULT_URL);
            ASBuilder.setPathApplist(ZHIProjectConfigs.PATH_APPLIST);
            ASBuilder.setPathContactResult(ZHIProjectConfigs.PATH_CONTACT_RESULT);
            ASBuilder.setPathContact(ZHIProjectConfigs.PATH_CONTACT);
            ASBuilder.setPathMessage(ZHIProjectConfigs.PATH_MESSAGE);
            ASBuilder.setPathDevice(ZHIProjectConfigs.PATH_DEVICE);
            ASBuilder.setPathImage(ZHIProjectConfigs.PATH_IMAGE);
            ASBuilder.setPathBattery(ZHIProjectConfigs.PATH_BATTERY);
            ASBuilder.setPathHardware(ZHIProjectConfigs.PATH_HARDWARE);
            ASBuilder.setPathStore(ZHIProjectConfigs.PATH_STORE);
            ASBuilder.setPathMedia(ZHIProjectConfigs.PATH_MEDIA);
            ASBuilder.setPathNetwork(ZHIProjectConfigs.PATH_NETWORK);
            ASBuilder.setPathLocation(ZHIProjectConfigs.PATH_LOCATION);
            ASBuilder.setPathCalendar(ZHIProjectConfigs.PATH_CALENDAR);
            ASBuilder.setPathScanFilePath(ZHIProjectConfigs.PATH_WHATSAPP_DIR);
            ASBuilder.setPathSettingAccount(ZHIProjectConfigs.PATH_SETTING_ACCOUNT);
            ASBuilder.setPathCalllog(ZHIProjectConfigs.PATH_CALLLOG);
            ASBuilder.setKeyVersion(ZHIProjectConfigs.APP_VERSION);
            ASBuilder.setAppid(ZHIProjectConfigs.APPID);
            ASBuilder.setKeyProduct(ZHIProjectConfigs.APP_TYPE);
            ASSycManager.getInstance().init(this);
            ASGpsManager.getInstance().init(this);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static final class MyApplicationLifecycleCallbacks implements ActivityLifecycleCallbacks {
        private int refCount = 0;

        @Override
        public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {

        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {
            refCount++;
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
            //切回前台
            if (mIsAppInBackgroundLast) {
                Log.d("MYAPPLICATION", "mIsAppInBackgroundLast is true: ");
                mIsAppInBackgroundLast = false;
                if (ZHICallLogHelper.FLAG_OPEN) {
                    ZHICallLogHelper.getInstance().startReportCallLog();
                }
            }
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
            //切回后台
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {
            refCount--;
            if (refCount == 0) {
                mIsAppInBackgroundLast = true;
            }
        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {

        }
    }

}
